# Create a database instance, and connect to it.
import asyncio
from urllib.parse import quote

from databases import Database
from databases.core import Connection
from databases.backends.mysql import MySQLConnection
import contextvars

database = Database(f'mysql://root:{quote("kexin@kexin2021")}@192.168.1.80/learn_db')

async def main():
    await database.connect()

    ctx = contextvars.ContextVar('Id of request.')

    # await asyncio.sleep(10000)

    async with database.connection() as connection:
        # print('"1" or id=28', '23'.translate())
        pass
        # print(connection.raw_connection)
        # print(connection.raw_connection.escape('"1" or id=28'))
    # await database.disconnect()

    # # Create a table.
    # query = """CREATE TABLE HighScores (id INTEGER PRIMARY KEY, name VARCHAR(100), score INTEGER)"""
    # await database.execute(query=query)

    # Insert some data.
    query = "INSERT INTO HighScores(name, score) VALUES (:name, :score)"
    values = [
        {"name": "Daisy", "score": 92},
        {"name": "Neil", "score": 87},
        {"name": "Carol", "score": 43},
    ]

    # for i in range(100):
    #     await database.execute_many(query, values)
    # await database.disconnect()
    # return
    # Run a database query.
    print('sdsdsdsd')
    query = "SELECT * FROM HighScores limit 3"
    query2 = 'SELECT * FROM HighScores limit 2'

    ctx.set('12')
    async def task():
        print('task start---', ctx.get(), asyncio.current_task())


        await asyncio.sleep(4)
        print(id(database.connection()))
        res = await database.fetch_all(query2)

        print('task over---')

    async def task2():
        print('task2 start---')
        async for i in database.iterate(query):
            await asyncio.sleep(2)
            print('i', i)

        print('task2 over---')

    async def task3():
        print('task2 start---')
        async with database.connection() as conn:
            print(id(conn))
            async for i in conn.iterate(query):
                await asyncio.sleep(2)
                print('i', i)
        print('task2 over---')

    # ta = asyncio.create_task(task())
    # ta2 = asyncio.create_task(task2())
    # ta3 = asyncio.create_task(task3())

    await asyncio.gather(task(), task3())
    # await ta
    # await ta2
    # await ta3
    # async for i in database.iterate(query):
    #     await asyncio.sleep(2)
    #     print('i', i)
    # res = await database.fetch_all(query)
    # print(res, '<-res2')


    await database.disconnect()

asyncio.run(main())
